#include "ThreadPool.h"
#include <stdio.h>

//初始化线程池
struct ThreadPool* threadPoolInit(struct EventLoop* mainLoop, int count)
{
    struct ThreadPool* pool = (struct ThreadPool*)malloc(sizeof(struct ThreadPool));
    pool->index = 0;
    pool->isStart = false;
    pool->mainLoop = mainLoop;
    pool->threadNum = count;
    pool->workerThreads = (struct WorkerThread*)malloc(sizeof(struct WorkerThread) * count);
    return pool;
}

//启动线程池
void threadPoolRun(struct ThreadPool* pool)
{
    assert(pool && !pool->isStart);
    //判断是否是主线程
    if(pool->mainLoop->threadID != pthread_self())
    {
        exit(0);
    }
    pool->isStart = true;
    if(pool->threadNum)
    {
        //初始化并启动线程
        for(int idx = 0; idx < pool->threadNum; idx++)
        {
            workerThreadInit(&pool->workerThreads[idx], idx);
            workerThreadRun(&pool->workerThreads[idx]);
        }
    }
}

//取出线程池中的某个反应堆实例
struct EventLoop* takeWorkerEventLoop(struct ThreadPool* pool)
{
    assert(pool->isStart);
    //判断是否是主线程
    if(pool->mainLoop->threadID != pthread_self())
    {
        exit(0);
    }

    struct EventLoop* evLoop = pool->mainLoop;
    //从线程池中找出一个子线程，然后取出里面的反应堆实例
    if(pool->threadNum > 0)
    {
        evLoop = pool->workerThreads[pool->index].evLoop;
        pool->index = ++pool->index % pool->threadNum;//平均分配
    }
    return evLoop;
}
